from django.db import models, connection
from tagging.models import TaggedItem, Tag, TagManager

class MetaTagManager(models.Manager):
    def most_active(self, content_type_id, num):
        select_query = {'tag_count': \
                        """SELECT COUNT(*) FROM %(tagged_item)s
                        WHERE %(tag)s.id = %(tagged_item)s.tag_id
                        AND %(tagged_item)s.content_type_id = %(content_type_id)s
                        """ % {
                            'tagged_item' : connection.ops.quote_name(TaggedItem._meta.db_table),
                            'tag' : connection.ops.quote_name(self.model._meta.db_table),
                            'content_type_id' : content_type_id
                            }
                        }
                        
        active_tags = self.model.objects.all().extra(select = select_query).order_by('-tag_count')[0:num]
        return active_tags

Tag.meta_objects = MetaTagManager()
Tag.meta_objects.model = Tag